<?php
class ldapModel extends model
{
    // 通过UID和passwd验证用户登录
    // 验证成功返回Success，失败返回ldap error message
    public function identify($config, $dn, $pwd)
    {
        $ret = '';
        $ds = ldap_connect($config->host);
        if ($ds) {
            ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
            ldap_set_option($ds,LDAP_OPT_REFERRALS,0);
            ldap_bind($ds, $dn, $pwd);
            $ret = ldap_error($ds);
            ldap_close($ds);
        }  else {
            $ret = ldap_error($ds);
        }
        return $ret;
    }
    
    // 通过UID获取用户DN信息
    // 参数：配置文件，用户UID
    // 返回用户DN信息或者null
    public function getUserDN($config, $account)
    {
        $ret = null;
        $ds = ldap_connect($config->host);
        if ($ds) {
            ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
            ldap_set_option($ds,LDAP_OPT_REFERRALS,0);
            $ret = ldap_bind($ds, $config->bindDN, $config->bindPWD);
            // $filter = "(uid=$account)";
            $rlt = ldap_search($ds, $config->baseDN, $config->uid.'='.$account);
            $count = ldap_count_entries($ds, $rlt);
            if($count > 0){
                $data = ldap_get_entries($ds, $rlt);
                $ret = $data[0]['dn'];
                $str = serialize($data);
            }
            ldap_unbind($ds);
        }
        return $ret;
    }
    
    // 添加新用户到禅道数据库
    public function addUserToZenTaoDB($config, $data, $password){
        $pass = true;
        $user = new stdclass();
        $user->account = $data[0][$config->uid][0];
        $user->password = md5($password);
        $user->email = $data[0][$config->mail][0];
        $user->realname = $data[0][$config->name][0];
        $this->dao->insert(TABLE_USER)->data($user)->autoCheck()->exec();
        if(dao::isError()) 
        {
            echo js::error(dao::getError());
            die(js::reload('parent'));
            $pass = false;
        }
        return $pass;
    }

    // 获取LDAP用户信息
    public function getUserMessageFromLDAP($config, $account)
        {
        $ds = ldap_connect($config->host);
        if ($ds) {
            ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
            ldap_set_option($ds,LDAP_OPT_REFERRALS,0);
            ldap_bind($ds, $config->bindDN, $config->bindPWD);
            $filter = "(|(sn=*))";
            $rlt = ldap_search($ds, $config->baseDN, $account);
            $data = ldap_get_entries($ds, $rlt);
            return $data;
        }
        return null;
    }
    
    // 判断当前用户是否存在于禅道数据库
    // 参数：用户UID
    // 成功返回true，失败返回false
    public function isExistInZenTaoDB($account)
    {
        $pass = false;
        $record = $this->dao->select('*')->from(TABLE_USER)
                ->where('account')->eq($account)
                ->andWhere('deleted')->eq(0)
                ->fetch();
        if($record){
            $pass = true;
        }
        return $pass;
    }
	
	// 更新用户信息
    public function updateUserDB($config, $account, $password, $data){
        $record = $this->dao->select('*')->from(TABLE_USER)
            ->where('account')->eq($account)
            ->andWhere('deleted')->eq(0)
            ->fetch();
        $user = $record;
        $ip   = $this->server->remote_addr;
        $password = md5($password);
        $relname = $data[0][$config->name][0];
        $email = $data[0][$config->mail][0];
        $last = $this->server->request_time;
        $this->dao->update(TABLE_USER)->set('password')->eq($password)
            ->set('email')->eq($email)
            ->set('realname')->eq($relname)
            ->set('visits = visits + 1')
            ->set('ip')->eq($ip)
            ->set('last')->eq($last)
            ->where('account')->eq($account)
            ->exec();
        $user->last = date(DT_DATETIME1, $user->last);
       }

    // 设置新增用户默认权限，默认权限为guest
    // 参数：account
    public function setDefaultUserGroup($account){
        $data = new stdclass();
        $data->account = $account;
        $data->group = 11;
        $this->dao->insert(TABLE_USERGROUP)->data($data)->exec();
    }
	
	// 自动同步用户权限
	public function setDefaultsUserGroup($account, $group){
        $data = new stdclass();
        $data->account = $account;
        $data->group = $group;
        $this->dao->insert(TABLE_USERGROUP)->data($data)->exec();
    }

	// 同步用户信息
    public function syncUsers()
    {
        $ds = ldap_connect($this->config->ldap->host);
        if ($ds) {
            ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
            ldap_set_option($ds,LDAP_OPT_REFERRALS,0);
            $ldapbind = ldap_bind($ds, $this->config->ldap->bindDN, $this->config->ldap->bindPWD);
            if ($ldapbind) {
                $filter = "(uid=*)";
                $rlt = ldap_search($ds, $this->config->ldap->baseDN, $filter);
                $users = ldap_get_entries($ds, $rlt);
                for ($i=0; $i<$users["count"]; $i++) {
                    if ($this->isExistInZenTaoDB($users[$i]["uid"][0])){
                        // 存在
                    } else {
                        // 不存在，添加到禅道DB后进行登录
                        $account = $users[$i]["uid"][0];
                        $data = $this->getUserMessageFromLDAP($this->config->ldap,$this->config->ldap->uid.'='.$account);
                        $addUser = $this->addUserToZenTaoDB($this->config->ldap, $data, $users[$i]["userpassword"][0]);
                        // 设置用户默认权限
                        $this->setDefaultsUserGroup($account, 11);
                    }
                }
			}
            ldap_unbind($ds);
        }
    }
}